﻿using Forum.Model.Entity;
using Forum.Model.Pager;
using Forum.Model.Request;
using Forum.Repository.Extensions;
using Forum.Repository.Interface;
using Forum.Service.Interface;
using SqlSugar;

namespace Forum.Service.Service
{
    public class VisitRecordService : IVisitRecordService
    {
        private readonly IAppRepository<VisitRecord> Repository;

        public VisitRecordService(IAppRepository<VisitRecord> appRepository)
        {
            Repository = appRepository;
        }

        public VisitRecord? GetById(int id)
        {
            return Repository.FindEntity(a => a.Id == id);
        }

        public List<VisitRecord> GetAll()
        {
            return Repository.GetList().OrderByDescending(a => a.Time).ToList();
        }

        public IPagedList<VisitRecord> GetPagedList(VisitRecordQueryParameters param)
        {
            var querySet = Repository.SugarQueryable;

            // 搜索
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.RequestPath.Contains(param.Search));
            }

            // 排序
            if (!string.IsNullOrEmpty(param.SortBy))
            {
                // 是否升序
                var ascending = !param.SortBy.StartsWith("-") ? " asc" : " desc";
                var orderByProperty = param.SortBy.Trim('-');

                querySet = querySet.OrderBy(orderByProperty + ascending);
            }

            return querySet.ToPage(param.Page, param.PageSize);
        }

        /// <summary>
        /// 总览数据
        /// </summary>
        /// <returns></returns>
        public object Overview()
        {
            ISugarQueryable<VisitRecord> GetQuerySet() => Repository.SugarQueryable.Where(a => a.RequestPath.StartsWith("/media"));

            return new
            {
                TotalVisit = GetQuerySet().Count(),
                TodayVisit = GetQuerySet().Where(a => a.Time.Date == DateTime.Today).Count(),
                YesterdayVisit = GetQuerySet().Where(a => a.Time.Date == DateTime.Today.AddDays(-2).Date).Count(),
            };
        }

        /// <summary>
        /// 趋势数据
        /// </summary>
        /// <param name="days">查看最近几天的数据，默认7天</param>
        /// <returns></returns>
        public object Trend(int days = 7)
        {
            //return Repository.SugarQueryable
            //    .Where(a => !a.RequestPath.StartsWith("/Api"))
            //    .Where(a => a.Time.Date > SqlFunc.DateAdd(DateTime.Today, 0-days, DateType.Day)).ToList();
            var list = Repository.SugarQueryable
                .Where(a => a.RequestPath.StartsWith("/media"))
                .Where(a => a.Time.Date > DateTime.Today.AddDays(0 - days).Date)
                .GroupBy(a => a.Time.Date)
                .Select(a => new
                {
                    time = a.Time.Date,
                    date = a.Time.Date.ToString("MM-dd"),
                    count = SqlFunc.AggregateCount(a.Id)
                })
                .ToList();
            for (int i = 1; i <= days; i++)
            {
                var date = DateTime.Today.AddDays(0 - i).Date;
                if (list.Where(a => a.time == date).Any())
                {
                    continue;
                }
                list.Add(new
                {
                    time = date,
                    date = date.ToString("MM-dd"),
                    count = 0
                });
            }
            return list.OrderBy(a => a.time).ToList();
        }

        /// <summary>
        /// 统计数据
        /// </summary>
        /// <returns></returns>
        public object Stats(DateTime date)
        {
            var data = Repository.SugarQueryable.Where(a => a.Time.Date == date.Date && a.RequestPath.StartsWith("/media"));
            return new { Count = data.Count() };
        }
    }
}
